<?php
namespace app\admin\controller;

use app\admin\model\AuthGroup as AuthGroupModel;
use app\admin\model\AuthRule as AuthRuleModel;
use think\Db;

class AuthGroup extends Common
{

    public function lst()
    {
        $authGroupRes = AuthGroupModel::paginate(3);
        $this->assign('authGroupRes',$authGroupRes);
        return view('list');
    }

    public function add()
    {
        if(request()->isPost()){
            $data = input('post.');
            if($data['rules']){
                $data['rules']= implode(',', $data['rules']);
            }
            $add = db('auth_group')->insert($data);
            if($add){
                $this->success('添加用户组成功',url('lst'));
            }else{
                $this->error('添加用户组失败');
            }
            return;
        }
        $authRule = new AuthRuleModel();
        $authRuleres = $authRule->authRuleTree();
        $this->assign('authruleres',$authRuleres);
        return view();
    }


    public function edit($id)
    {
        if(request()->isPost()){
            $data = input('post.');
            if($data['rules']){
                $data['rules'] = implode(',',$data['rules']);
            }
            #另一种实现方法, 当提交的数据里面没有status时候,将$data['status']赋值为0
            // $_data=array();
            // foreach($data as $k=>$v){
            //     $_data[]=$k;
            // }
            // if(!in_array('status',$_data)){
            //     $data['status']=0;
            // }
            #另一种实现方法,
            if(!isset($data['status']) ){
                $data['status'] = 0;
            }
             $edit = db('auth_group')->update($data);
             if($edit !==false){
                 $this->success('修改用户组成功',url('lst'));
             }else{
                 $this->error('修改用户组失败');
             }
             return;
        }
        $authgroups =  db('auth_group')->find($id);
        $authrules =  new AuthRuleModel();
        $authruleres = $authrules->authRuleTree();
        $this->assign(array(
            'authruleres'=>$authruleres,
            'authgroups'=>$authgroups
        ));
        return view();
    }

    public function del($id)
    {
        $del = db('auth_group')->delete($id);
        if($del){
            $this->success('删除用户组成功',url('lst'));
        }else{
            $this->error('删除用户组失败');
        }

    }




}
